package cn.jsu.oj.judgment.parsing;

import cn.jsu.oj.judgment.utils.AnnotationPackageScanUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author suixuexue, ahtonc
 */
@Slf4j
public class PackAuthorize {
    private static final Map<Short, Class<?>> PACK_MAP = new HashMap<>();
    private static PackAuthorize instance;

    /**
     * 扫描注解注册类映射
     */
    private PackAuthorize() {
        //扫描使用packType的类
        List<Class<?>> list = AnnotationPackageScanUtil.scanPackage("cn", PackType.class);
        //将class注册到Map中
        list.forEach((clazz) -> {
            short typeNo = clazz.getAnnotation(PackType.class).typeNo();
            if (PACK_MAP.containsKey(typeNo)) {
                log.error("PackType编号重复注册");
                System.exit(-1);
            } else {
                PACK_MAP.put(typeNo, clazz);
            }
        });
    }

    /**
     * 通过懒加载的方式获取类型实例
     */
    public static PackAuthorize getInstance() {
        if (instance == null) {
            synchronized (PackAuthorize.class) {
                if (instance == null) {
                    instance = new PackAuthorize();
                }
            }
        }
        return instance;
    }

    /**
     * 获取映射Map
     */
    public Map<Short, Class<?>> getPackMap() {
        return PACK_MAP;
    }

    /**
     * 通过包编号获取class
     * @param packType 包编号
     * @return 包编号对应的class
     */
    public Class<?> getClass(short packType) {
        return PACK_MAP.get(packType);
    }
}
